package org.iabako.server.servlet;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.poi.util.IOUtils;
import org.iabako.server.serviceimpl.security.SessionUser;
import org.iabako.shared.iservice.user.SignUpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by jose on 09/02/15.
 */
public class UploadEnterpriseLogo extends HttpServlet {

    static Logger log = Logger.getLogger(PaymentSuccessServlet.class.getName());

    @Autowired
    SignUpService signUpService;

    @Autowired
    SessionUser sessionUser;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletFileUpload upload = new ServletFileUpload();
        //File size max = 1MB
        upload.setFileSizeMax(1024 * 1024);

        try {
            FileItemIterator iterator = upload.getItemIterator(request);

            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream input = item.openStream();

                boolean png = false;
                boolean gif = false;
                boolean jpg = false;
                if (item.getContentType() == null
                        || !((png = item.getContentType().toLowerCase().contains("png"))
                        || (gif = item.getContentType().toLowerCase().contains("gif"))
                        || (jpg = item.getContentType().toLowerCase().contains("jpg")
                        || item.getContentType().toLowerCase().contains("jpeg")))) {

                    errorHandle();
                    return;
                }

                BufferedImage image;
                try {
                    image = ImageIO.read(input);
                } catch (Exception e) {
                    log.warn("It seems like someone try to upload a file bigger than 1 MB...");
                    errorHandle();
                    return;
                }

                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(image, png ? "png" : gif ? "gif" : "jpg", os);

                InputStream inputStreamFromResizeImage = new ByteArrayInputStream(os.toByteArray());

                sessionUser.getUser().getEnterprise().setLogo(IOUtils.toByteArray(inputStreamFromResizeImage));
                sessionUser.getUser().getEnterprise().setContentTypeLogo(item.getContentType());

                input.close();
                os.close();
                inputStreamFromResizeImage.close();

                signUpService.saveEnterprise(sessionUser.getUser().getEnterprise());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    private void errorHandle() {
        //We clean image in BD to indicate client side that there was an error
        sessionUser.getUser().getEnterprise().setLogo(null);
        sessionUser.getUser().getEnterprise().setContentTypeLogo(null);
        signUpService.saveEnterprise(sessionUser.getUser().getEnterprise());
    }
}
